#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>

#define PORT 12345

void *receive_messages(void *arg) {
    int client_socket = *((int *)arg);
    char buffer[1024];

    while (1) {
        // Receive message from client
        int receive_size = recv(client_socket, buffer, sizeof(buffer), 0);

        if (receive_size > 0) {
            buffer[receive_size] = '\0';
                    printf("Client says: %s", buffer);
        } else if (receive_size == 0) {
            printf("Client disconnected\n");
            break;
        }
    }

    close(client_socket);
    pthread_exit(NULL);
}

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    pthread_t tid_receive;

    // Create socket
    if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    // Setup server address
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // Bind the socket
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Bind failed");
        exit(EXIT_FAILURE);
    }

    // Listen for incoming connections
    if (listen(server_socket, 5) == -1) {
        perror("Listen failed");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    // Accept connection from client
    socklen_t client_addr_len = sizeof(client_addr);
    if ((client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len)) == -1) {
        perror("Accept failed");
        exit(EXIT_FAILURE);
    }

    // Create a thread to receive messages from the client
    pthread_create(&tid_receive, NULL, receive_messages, &client_socket);

    // Send messages to the client
    char message[1024];

    while (1) {
        //printf("Enter message to send to client (type 'exit' to quit): ");
        fgets(message, sizeof(message), stdin);

        // Send the message to the client
        send(client_socket, message, strlen(message), 0);

        // Check if the user wants to exit
        if (strncmp(message, "exit", 4) == 0) {
            break;
        }
    }

    // Close the server socket
    close(server_socket);

    return 0;
}
